package cn.it.controller;

import cn.it.constant.MessageConstant;
import cn.it.entity.Result;
import cn.it.service.UserService;
import com.alibaba.dubbo.config.annotation.Reference;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.User;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.swing.*;


@RestController
@RequestMapping("/user")
public class UserController {

    @Reference
    private UserService userService;

    @RequestMapping(value = "/getUsername", name = "获得当前登录用户的用户名")
    public Result getUsername() {
        //当Spring security完成认证后，会将当前用户信息保存到框架提供的上下文对象
        User user = (User) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        if (user != null) {
            String username = user.getUsername();
            return new Result(true, MessageConstant.GET_USERNAME_SUCCESS, username);
        }
        return new Result(false, MessageConstant.GET_SETMEAL_LIST_FAIL);
    }

    @RequestMapping(value = "/findById", name = "获得当前登录用户的用户名")
    public Result findById(Integer id) {
        try {
            cn.it.pojo.User user = userService.findById(id);
            return new Result(true, "编辑用户信息", user);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, "用户信息回显失败");
        }
    }


    @RequestMapping(value = "/edit", name = "编辑用户信息")
    public Result edit(Integer[] roleIds, @RequestBody cn.it.pojo.User user) {
        try {
            userService.edit(roleIds, user);
            return new Result(true, "编辑用户成功");
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, "编辑用户失败");
        }
    }

    @RequestMapping(value = "/deleteById", name = "删除用户信息及管理角色信息")
    public Result deleteById(Integer id) {
        try {
            userService.deleteById(id);
            return new Result(true,"删除用户和角色信息");
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false,"删除用户和角色失败");
        }

    }
}
